package com.zfzs.post.modules.goods.service.impl;

import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.model.vo.GoodsOrderVO;
import com.zfzs.post.modules.address.domain.AgentArea;
import com.zfzs.post.modules.address.service.AgentAreaService;
import com.zfzs.post.modules.goods.domain.GoodOrder;
import com.zfzs.post.modules.goods.domain.GoodOrderSn;
import com.zfzs.post.modules.goods.domain.Goods;
import com.zfzs.post.modules.goods.service.GoodOrderService;
import com.zfzs.post.modules.goods.service.GoodOrderSnService;
import com.zfzs.post.modules.goods.service.GoodsOrderWebService;
import com.zfzs.post.modules.goods.service.GoodsService;
import com.zfzs.post.modules.goods.service.dto.GoodOrderQueryCriteria;
import com.zfzs.post.modules.goods.service.dto.HandleOrderDTO;
import com.zfzs.post.modules.post.domain.TerminalInfo;
import com.zfzs.post.modules.post.service.TerminalService;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.utils.SecurityUtils;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wq
 * @date 2019/11/19 20:22
 * @description
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GoodsOrderWebServiceImpl implements GoodsOrderWebService {

    @Autowired
    private GoodOrderService goodOrderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private AgentAreaService agentAreaService;

    @Autowired
    private TerminalService terminalService;

    @Autowired
    private GoodOrderSnService goodOrderSnService;


    @Override
    public Map<String, Object> getGoodsOrderPage(GoodOrderQueryCriteria criteria, Integer page, Integer size) {
        Map<String, Object> map = new HashMap<>();
        JpaPageHelper<GoodsOrderVO> pageHelper = goodOrderService.findGoodsOrderPage(criteria, page, size);
        List<Map<String, Object>> result = pageHelper.getResult();
        for (Map<String, Object> o : result) {
            String id = o.get("goodsId").toString();
            Goods g = goodsService.findById(id);
            if (g != null) {
                o.put("goodsName", g.getName());
            }
        }
        map.put("content", pageHelper.getResult());
        map.put("totalElements", pageHelper.getTotalCount());
        return map;
    }

    @Override
    public void handleOrder(HandleOrderDTO dto) {
        //分配人
        Long agentId = dto.getAgentId();
        //相关订单id
        Integer orderId = dto.getOrderId();

        GoodOrder order = goodOrderService.findById(orderId);
        if (order == null) {
            throw new BadRequestException("未查询到订单");
        }
        //开始sn
        List<String> startList = dto.getStartList();
        //结束sn
        List<String> endList = dto.getEndList();
        //单个sn
        List<String> aloneList = dto.getAloneList();

        Long channelId = SecurityUtils.getUserId();

        if (startList != null && aloneList != null) {
            if (startList.size() == 1 && StringUtils.isBlank(startList.get(0)) && aloneList.size() == 1 && StringUtils.isBlank(aloneList.get(0))) {
                throw new BadRequestException("请填写终端号");
            }
        }

        Integer count = 0;

        if (startList != null && !startList.isEmpty() && StringUtils.isNotBlank(startList.get(0))) {
            if (endList != null && !endList.isEmpty() && StringUtils.isNotBlank(endList.get(0))) {
                if (startList.size() == endList.size()) {
                    for (int i = 0; i < startList.size(); i++) {
                        String startSn = startList.get(i);
                        String endSn = endList.get(i);
                        List<TerminalInfo> list = terminalService.findByStartAndEnd(startSn, endSn, channelId);
                        terminalService.updateTerminalOwner(agentId, list);
                        terminalService.distribuSn(agentId, list, channelId);
                        //添加订单关联
                        addOrderSnList(list, agentId, channelId, order.getOrderNo());
                        count += list.size();
                    }
                }
            }
        }

        if (aloneList != null && !aloneList.isEmpty() && StringUtils.isNotBlank(aloneList.get(0))) {
            for (String s : aloneList) {
                List<TerminalInfo> list = terminalService.findByStartAndEnd(s, s, channelId);
                terminalService.updateTerminalOwner(agentId, list);
                terminalService.distribuSn(agentId, list, channelId);
                //添加订单关联
                addOrderSnList(list, agentId, channelId, order.getOrderNo());
                count += list.size();
            }
        }

        if (count > 0) {
            order.setStatus(3);
            goodOrderService.update(order);
        }
    }

    public void addOrderSnList(List<TerminalInfo> list, Long agentId, Long channelId, String orderNo) {

        for (TerminalInfo terminalInfo : list) {

            GoodOrderSn goodOrderSn = new GoodOrderSn();
            goodOrderSn.setAgentId(agentId);
            goodOrderSn.setChannelId(channelId);
            goodOrderSn.setSn(terminalInfo.getSn());
            goodOrderSn.setOrderNo(orderNo);

            goodOrderSnService.create(goodOrderSn);
        }
    }


    @Override
    public Map<String, Object> queryOrderInfo(Integer orderId) {
        GoodOrder order = goodOrderService.findById(orderId);

        AgentArea area = agentAreaService.findById(order.getAreaId());

        if (area == null) {
            throw new BadRequestException("未查询到收货地址");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("address", area);
        return result;
    }
}
